<template>
  <div class="enterprise-list-wrapper">
    <!-- 顶部导航栏 -->
    <HomeNavBar />
    
    <div class="enterprise-list-container">
      <!-- 页面头部 -->
      <div class="page-header">
        <div class="header-content">
          <div class="header-text">
            <h1 class="page-title">企业展示</h1>
            <p class="page-desc">发现优秀企业，开启职业新征程</p>
          </div>
          <el-button 
            v-if="store.app.role !== 'enterprise'"
            type="primary" 
            :icon="Plus" 
            @click="goToCreate"
            class="create-button"
          >
            创建企业
          </el-button>
        </div>
      </div>

      <!-- 搜索和筛选 -->
      <el-card class="filter-card" shadow="never">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索企业名称..."
              :prefix-icon="Search"
              clearable
              @keyup.enter="handleSearch"
              @clear="handleSearch"
            />
          </el-col>
          <el-col :span="6">
            <el-select v-model="statusFilter" placeholder="状态筛选" clearable @change="handleSearch">
              <el-option label="全部" value="" />
              <el-option label="活跃" value="active" />
              <el-option label="暂停" value="inactive" />
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
          </el-col>
        </el-row>
      </el-card>

      <!-- 企业列表 -->
      <div class="enterprise-grid" v-loading="loading">
        <el-card
          v-for="enterprise in enterpriseList"
          :key="enterprise.enterpriseId"
          class="enterprise-card"
          shadow="hover"
          @click="viewEnterpriseDetail(enterprise.enterpriseId)"
        >
          <div class="enterprise-header">
            <div class="enterprise-logo">
              <el-image
                :src="getImageUrl(enterprise.imageUrl)"
                :alt="enterprise.enterpriseName"
                fit="cover"
                class="logo-image"
              >
                <template #error>
                  <div class="image-slot">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
            </div>
            <div class="enterprise-info">
              <h3 class="enterprise-name">{{ enterprise.enterpriseName }}</h3>
              <el-tag
                :type="enterprise.status === 'active' ? 'success' : 'info'"
                size="small"
                class="status-tag"
              >
                {{ enterprise.status === 'active' ? '活跃' : '暂停' }}
              </el-tag>
            </div>
          </div>
          
          <div class="enterprise-description">
            <p>{{ truncateText(enterprise.description, 100) }}</p>
          </div>

          <div class="enterprise-footer">
            <div class="enterprise-rating" v-if="enterprise.rating">
              <el-icon><StarFilled /></el-icon>
              <span>{{ enterprise.rating.toFixed(1) }}</span>
            </div>
            <div class="enterprise-date">
              <el-icon><Calendar /></el-icon>
              <span>{{ formatDate(enterprise.createTime) }}</span>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 空状态 -->
      <el-empty v-if="!loading && enterpriseList.length === 0" description="暂无企业信息" :image-size="200" />

      <!-- 分页 -->
      <div class="pagination-container" v-if="pagination.total > 0">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[12, 24, 48, 96]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Search, Picture, StarFilled, Calendar, Plus } from '@element-plus/icons-vue'
import HomeNavBar from '@/components/HomeNavBar.vue'
import instance from '@/utils/request'
import useStore from '@/store'

const router = useRouter()
const store = useStore()

// 数据
const loading = ref(false)
const enterpriseList = ref([])
const searchKeyword = ref('')
const statusFilter = ref('')
const pagination = ref({
  page: 1,
  pageSize: 12,
  total: 0
})

// 获取企业列表
const fetchEnterpriseList = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.value.page,
      pageSize: pagination.value.pageSize
    }
    
    if (searchKeyword.value) {
      params.keyword = searchKeyword.value
    }
    
    if (statusFilter.value) {
      params.status = statusFilter.value
    }

    const response = await instance.request({
      method: 'GET',
      url: '/enterprises',
      params
    })

    if (response.code === 0) {
      enterpriseList.value = response.data.enterprises || []
      if (response.data.pagination) {
        pagination.value.total = response.data.pagination.total || 0
      }
    } else {
      ElMessage.error(response.msg || '获取企业列表失败')
    }
  } catch (error) {
    console.error('获取企业列表失败:', error)
    ElMessage.error('获取企业列表失败，请重试')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.value.page = 1
  fetchEnterpriseList()
}

// 分页
const handlePageChange = (page) => {
  pagination.value.page = page
  fetchEnterpriseList()
  // 滚动到顶部
  window.scrollTo({ top: 0, behavior: 'smooth' })
}

const handleSizeChange = (size) => {
  pagination.value.pageSize = size
  pagination.value.page = 1
  fetchEnterpriseList()
}

// 查看企业详情
const viewEnterpriseDetail = (enterpriseId) => {
  router.push(`/enterprises/${enterpriseId}`)
}

// 跳转到创建企业页面
const goToCreate = () => {
  router.push('/enterprises/create')
}

// 获取图片URL
const getImageUrl = (url) => {
  if (!url) return ''
  if (url.startsWith('http')) return url
  return `http://localhost:7001${url}`
}

// 截断文本
const truncateText = (text, maxLength) => {
  if (!text) return '暂无描述'
  if (text.length <= maxLength) return text
  return text.substring(0, maxLength) + '...'
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  })
}

// 初始化
onMounted(() => {
  fetchEnterpriseList()
})
</script>

<style lang="scss" scoped>
.enterprise-list-wrapper {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.enterprise-list-container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 30px 20px;
}

// 页面头部
.page-header {
  margin-bottom: 40px;
  
  .header-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .header-text {
      text-align: left;
      
      .page-title {
        font-size: 32px;
        font-weight: 600;
        color: #303133;
        margin-bottom: 12px;
      }
      
      .page-desc {
        font-size: 16px;
        color: #909399;
        margin: 0;
      }
    }
    
    .create-button {
      height: 40px;
      padding: 0 24px;
    }
  }
}

// 筛选卡片
.filter-card {
  margin-bottom: 30px;
  border-radius: 8px;
  
  :deep(.el-card__body) {
    padding: 20px;
  }
}

// 企业网格
.enterprise-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 24px;
  margin-bottom: 40px;
}

// 企业卡片
.enterprise-card {
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s;
  overflow: hidden;
  
  &:hover {
    transform: translateY(-4px);
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
  }
  
  :deep(.el-card__body) {
    padding: 0;
  }
}

.enterprise-header {
  display: flex;
  align-items: center;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  
  .enterprise-logo {
    width: 60px;
    height: 60px;
    border-radius: 8px;
    overflow: hidden;
    background: rgba(255, 255, 255, 0.2);
    margin-right: 16px;
    flex-shrink: 0;
    
    .logo-image {
      width: 100%;
      height: 100%;
    }
    
    .image-slot {
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      background: rgba(255, 255, 255, 0.1);
      
      .el-icon {
        font-size: 24px;
        color: rgba(255, 255, 255, 0.8);
      }
    }
  }
  
  .enterprise-info {
    flex: 1;
    min-width: 0;
    
    .enterprise-name {
      font-size: 18px;
      font-weight: 600;
      margin: 0 0 8px 0;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    
    .status-tag {
      margin-top: 4px;
    }
  }
}

.enterprise-description {
  padding: 16px 20px;
  min-height: 60px;
  
  p {
    margin: 0;
    font-size: 14px;
    color: #606266;
    line-height: 1.6;
  }
}

.enterprise-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 20px;
  border-top: 1px solid #ebeef5;
  background-color: #fafafa;
  
  .enterprise-rating,
  .enterprise-date {
    display: flex;
    align-items: center;
    gap: 6px;
    font-size: 13px;
    color: #909399;
    
    .el-icon {
      font-size: 16px;
    }
  }
  
  .enterprise-rating {
    color: #f56c6c;
    
    .el-icon {
      color: #f7ba2a;
    }
  }
}

// 分页
.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 40px;
  padding: 20px 0;
}

// 响应式
@media (max-width: 768px) {
  .enterprise-grid {
    grid-template-columns: 1fr;
    gap: 16px;
  }
  
  .page-header .page-title {
    font-size: 24px;
  }
}
</style>

